import Vue from 'vue'
import store from '../store'
import VueRouter from 'vue-router'
import User from '../views/user/user'
import Main from '../views/index/main'
import Detail from '../views/index/detail'
import Shop from '../views/shopping/shop'
import MyOrderList from '../views/myorder/myorderlist'
import Sell from '../views/sell/sell'
// user子路由
import Info from '../views/user/components/info'
import ChangePwd from '../views/user/components/changepwd'
import MyOrder from '../views/user/components/myorder'
import MySellOrder from '../views/user/components/mysellorder'
import Address from '../views/user/components/address'
import SellBooks from '../views/user/components/sellbooks'
// 购物子路由
import ShopCart from '../views/shopping/components/shopcart'
import Fill from '../views/shopping/components/fill'
import Complete from '../views/shopping/components/complete'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/main' },
  {
    path: '/main',
    component: Main
  },
  {
    path: '/detail',
    component: Detail
  },
  {
    path: '/user',
    component: User,
    children: [
      { path: '/', redirect: '/info' },
      { path: '/info', component: Info },
      { path: '/changepwd', component: ChangePwd },
      { path: '/myorder', component: MyOrder },
      { path: '/mysellorder', component: MySellOrder },
      { path: '/address', component: Address },
      { path: '/sellbooks', component: SellBooks }
    ]
  },
  {
    path: '/shop',
    component: Shop,
    children: [
      { path: '/', redirect: '/shopcart' },
      { path: '/shopcart', component: ShopCart },
      { path: '/fill', component: Fill },
      { path: '/complete', component: Complete }
    ]
  },
  {
    path: '/myorderlist',
    component: MyOrderList
  },
  {
    path: '/sell',
    component: Sell
  }
]

const router = new VueRouter({
  routes
})

// 避免路由冗余 从本身路由跳转到本身
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数 表示放行
  // next() 放行     next('/login') 强制跳转

  if (to.path === '/main') return next()
  if (to.path === '/detail') return next()

  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    store.commit('user/setShowLogin', true)
    return next('/main')
  }
  next()
})
export default router
